package com.aaa.sso.service;

import com.aaa.entity.Menu;
import com.aaa.entity.User;
import com.aaa.sso.feign.RoleMenuFeign;
import com.aaa.sso.feign.UserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author 崔灿
 * @Date 2023/02/25 10:11
 * @ClassName UserService
 * @Description
 * @Version 1.0
 */

@Service
public class UserService implements UserDetailsService {

    @Autowired
    private UserFeign userFeign;
    @Autowired
    private RoleMenuFeign roleMenuFeign;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userFeign.getByName(s);
        if (user != null){
            List<Menu> menuByUserid = roleMenuFeign.getMenuByUserid(user.getUserId());
            Collection<SimpleGrantedAuthority> collect = menuByUserid.stream().filter(item->item.getPerms()!="").filter(item -> item.getParentId() != 0).map(item -> new SimpleGrantedAuthority(item.getPerms())).collect(Collectors.toList());
            org.springframework.security.core.userdetails.User users = new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),collect);
            return users;
        }
        return null;
    }
}
